package dev.caobaoqi6040.backend.modules.oss.service;

import dev.caobaoqi6040.backend.modules.oss.exception.BucketAlreadyExistException;
import dev.caobaoqi6040.backend.modules.oss.exception.BucketNotFoundException;
import dev.caobaoqi6040.backend.exception.OSSException;
import io.minio.*;
import io.minio.errors.MinioException;
import io.minio.messages.Bucket;
import io.minio.messages.Tags;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.List;

/**
 * BucketServiceImpl
 *
 * @author caobaoqi6040
 * @since 2025/9/21 17:16
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BucketServiceImpl implements BucketService {

	private final MinioClient minioClient;

	@Override
	public List<Bucket> listBuckets() {
		try {
			return minioClient.listBuckets();
		} catch (MinioException | GeneralSecurityException | IOException ex) {
			throw new OSSException(ex.getLocalizedMessage());
		}
	}

	@Override
	public Boolean bucketExist(String bucketName) {
		try {
			return minioClient.bucketExists(BucketExistsArgs.builder()
				.bucket(bucketName)
				.build());
		} catch (MinioException | GeneralSecurityException | IOException ex) {
			throw new OSSException(ex.getLocalizedMessage());
		}
	}

	@Override
	public Tags getTags(String bucketName) {
		if (!bucketExist(bucketName)) {
			throw new BucketNotFoundException(String.format("the bucket %s not found", bucketName));
		}
		try {
			return minioClient.getBucketTags(GetBucketTagsArgs.builder()
				.bucket(bucketName)
				.build());
		} catch (MinioException | GeneralSecurityException | IOException ex) {
			throw new OSSException(ex.getLocalizedMessage());
		}
	}


	@Override
	public void removeBucket(String bucketName) {
		if (!bucketExist(bucketName)) {
			throw new BucketNotFoundException(String.format("the bucket %s not found", bucketName));
		}
		try {
			minioClient.removeBucket(RemoveBucketArgs.builder()
				.bucket(bucketName)
				.build());
		} catch (MinioException | GeneralSecurityException | IOException ex) {
			throw new OSSException(ex.getLocalizedMessage());
		}
	}

	@Override
	public void makeBucket(String bucketName, String region, Boolean objectLock) {
		if (bucketExist(bucketName)) {
			throw new BucketAlreadyExistException(String.format("the bucket %s already exist", bucketName));
		}
		try {
			minioClient.makeBucket(MakeBucketArgs.builder()
				.bucket(bucketName)
				.region(region)
				.objectLock(objectLock)
				.build()
			);
		} catch (MinioException | GeneralSecurityException | IOException ex) {
			throw new OSSException(ex.getLocalizedMessage());
		}
	}

}
